package com.data.structure;

import java.util.Arrays;

public class Queue<E> {

    private Object[] data = null;
    private int maxSize; // 队列的容量
    private int front;   //对列头，允许删除
    private int rear;    //队列尾，允许插入

    public Queue(){
        this(10);
    }
    public Queue(int initialSize){
        if(initialSize>=0){
            this.maxSize = initialSize;
            data = new Object[initialSize];
            front = rear = 0;
        }else{
            throw new RuntimeException("初始化大小不能小于0:"+initialSize);

        }
    }

    //在队列的尾部插入元素
    public boolean add(E e){
        if(rear == maxSize){
            throw new RuntimeException("队列已满，无法插入新的元素!");
        }else{
            data[rear++]=e;
            System.out.println(Arrays.asList(data));
            return true;
        }
    }

    //队列头部杀出元素，出队

    public E poll(){
        if(empty()){
            throw new RuntimeException("空队列异常");
        }else{
            E value = (E) data[front]; //临时保存队列front端的元素值
            data[front++]=null;        //释放队列front端的元素
            System.out.println(Arrays.asList(data));
            return value;
        }
    }

    //获取队列头部元素,但不删除
    public E peek(){
        if(empty()){
            throw new RuntimeException("空队列异常");
        }else{
            return (E) data[front];
        }
    }

    private boolean empty(){
        if(data==null||data.length==0){
            return true;
        }
            return false;
    }

    public static void main(String[] args){
        Queue queue = new Queue();
        for(int i=100;i<108;i++){
            queue.add(i);
            if(i==105)
            queue.poll();
        }
    }

}
